<template>
    <div class="box">
        <div class="free-top">
            <div class="tag-box">
                <el-tag v-for="(val,index) in typeData" :type="val.type" :key="index" class="mx-1" @click="topTagFun(val.typeName)" style="margin-right:5px" effect="dark" round>
                    <strong>{{val.typeName}}</strong>
                </el-tag>
            </div>
        </div>
        <div class="search-box">
            <el-input v-model="leftArtDto.searchContent" @keyup.enter="leftSearchFnu" class="w-50 m-2 left-search" size="large" clearable placeholder="输入关键字回车搜索">
                <!-- <template #prefix>
                    <el-icon class="el-input__icon"><Search /></el-icon>
                </template> -->
            </el-input>
            <el-input v-model="rightSearch" @keyup.enter="rightSearchFnu" class="w-50 m-2 right-search" size="large" clearable placeholder="输入关键字搜索">
                <!-- <template #prefix>
                    <el-icon class="el-input__icon"><search /></el-icon>
                </template> -->
            </el-input>
        </div>
        <div class="free-box">
            <div class="art-left">                
                <div class="art-main card-box" v-for="(item,index) in freeArtDataList" :key="index">
                    <el-card shadow="hover" >
                        <img :src="avatarUrlPrefix + item.avatarName" alt="pic" style="width: 70px; height: 70px;border-radius:50%;margin-right: 5px;float:left" />
                        <p style="margin-top: 1%;color:skyblue;display:flex;align-items:center">
                            <strong>{{item.articleTitle}}</strong>        
                        </p>
                        <span>
                            <strong>作者：</strong>
                            {{item.articleUser}}
                        </span> &nbsp;
                        <span>
                            <strong>发布时间：</strong>
                            {{item.planetUpdateTime}}
                        </span>
                        <el-button color="#626aef" :dark="isDark" plain style="float:right" @click="developArticleDetail(item)">
                            展开详情
                            <el-icon v-if="item.articleId == currentArtId"><CaretRight /></el-icon>
                            <el-icon v-else><CaretLeft /></el-icon>
                        </el-button>
                    </el-card>
                </div>
                <el-affix target=".art-left" position="bottom" :offset="60" style="width: 100px">
                    <div class="affix-box">
                        <el-button type="success" v-if="isLogin" @click="checkLogin" style="padding-left:5px">
                            <el-icon><User /></el-icon>
                            登录/注册
                        </el-button>     
                        <el-button type="success" v-if="!isLogin" @click="changeRole" style="padding-left:5px">
                            <el-icon><User /></el-icon>
                            &nbsp;切换角色
                        </el-button>
                        <el-button type="primary" v-if="!isLogin" @click="manageAdmin" style="margin-top:10px;margin-left:0px;padding-left:5px;">
                            <el-icon><Monitor /></el-icon>
                            &nbsp;管理后台
                        </el-button>
                        <el-badge :value="10" class="item" type="warning" style="margin-top:10px;">
                            <el-button type="info" style="padding-left:5px;">
                                <el-icon size="17"><Bell /></el-icon>
                                &nbsp;系统消息  
                            </el-button>
                        </el-badge>
                        <el-button type="danger" v-if="!isLogin" @click="contactConsumeService" style="padding-left:5px;">
                            <el-icon><Service /></el-icon>
                            &nbsp;联系客服
                        </el-button>
                        <el-button type="warning" v-if="!isLogin" @click="userLogout" style="margin-top:10px;margin-left:0;padding-left:5px;">
                            <el-icon><Pointer /></el-icon>
                            &nbsp;退出登录
                        </el-button>
                    </div>
                </el-affix>       
            </div>        
            <div class="art-right">              
                <div class="art-con" style="height:100%">
                    <el-card class="box-card" style="height:100%">                       
                        <template #header>
                            <div class="card-header">
                                <span style="color: skyblue"><strong>内容详情</strong></span>
                                <el-button v-if="!isCollect" size="small" class="button" type="primary" @click="collectArtFun">
                                    点此收藏
                                    <el-icon size="18"><StarFilled color="#dcdcdc"/></el-icon>
                                </el-button>
                                <el-button v-if="isCollect" size="small" class="button" type="danger" @click="cancelCollectArtFun">
                                    已收藏
                                    <el-icon size="18"><StarFilled color="orange"/></el-icon>
                                </el-button>
                                
                                <el-button class="button" size="small" type="success" @click="flushArtList">点击刷新</el-button>
                            </div>
                        </template>
                        <div class="title-box">
                            <strong>标题：</strong>
                            <el-tag size="small" class="mx-1" effect="dark">
                                {{artDetailInfo.title}}
                            </el-tag>
                        </div>
                        <div class="right-type">
                            <strong>类型：</strong>
                            <el-tag type="warning" size="small" class="mx-1" effect="dark">
                                {{artDetailInfo.type}}
                            </el-tag>
                        </div>
                        <div class="right-detail">
                            <strong>详情：</strong>
                            {{artDetailInfo.articleContent}}
                        </div>
                        <div class="speak-detail">
                            <strong>评论列表：</strong>
                            <div class="detail">
                                <el-alert v-for="(val,index) in commentList" :key="index" :title="val.content" :closable="false" :type="val.userId==(userInfo==null?'':userInfo.userId)?'success':speakType" show-icon />
                            </div>
                        </div>
                        <PlanetComments @commentOk="getCommentVal" :currentArtId="currentArtId"/>
                    </el-card>  
                </div>    
            </div>
        </div>
        <el-dialog v-model="roleDialogVisible" title="角色列表" width="30%" draggable>
            <span>当前账号存在多个角色,请选择一个角色登录</span>
            <el-select v-model="selectRoleId" class="m-2" placeholder="请选择角色登录后台" clearable>
                <el-option
                    v-for="(item,index) in roleList"
                    :key="index"
                    :label="item.roleName"
                    :value="item.roleId"
                />
            </el-select>
            <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="confirmLogin">
                    确认切换
                </el-button>
            </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup >
import { ref,getCurrentInstance ,reactive, onMounted, computed} from "vue"
import { useDark } from '@vueuse/core'
import {$http} from '@/utils/axios.js'
import { gatewayPrefix, userMiddleContextPath, avatarUrlPrefix, currentUser,token, debounce} from '@/utils/commConstance'
import {getArticleType} from '@/utils/commDataFun'
import router from '@/router'
import { useStore } from 'vuex' 
import { ElMessage, ElMessageBox } from 'element-plus'
import PlanetComments from '@/components/sonComponent/PlanetComments.vue'
let userInfo = JSON.parse(sessionStorage.getItem(currentUser))
const store = useStore()
let typeData = ref([])
const isLogin = ref(true)
const loading = ref(true)
const isDark = ref(useDark())
const isDetail = ref(false)
const activeNames = ref(['1'])
const speakType = ref('info')
let leftArtDto = reactive({
    searchContent: '',
    page: 1,
    size: 20
})
const rightSearch = ref('')
let freeArtDataList=ref([])
let currentArtId=ref('')
const currentArtUserId=ref()
let artDetailInfo=reactive({})
let commentList=ref([])
const isCollect = ref(false)
const roleDialogVisible=ref(false)
const roleList = ref([])
const selectRoleId = ref('')
onMounted(()=>{
    getArticleType()
    if(userInfo == null){
        isLogin.value = true
        getAllFreeArtByPage()
    }else{
        isLogin.value = false
        getAllLoginArtByPage()
    }          
    setTimeout((()=>{
        typeData.value = store.state.artTypeList
    }),500)
})
//顶部标签搜索
const topTagFun = debounce((val)=>{
    leftArtDto.searchContent = val
    getAllFreeArtByPage()
},500)

//登录
const checkLogin = ()=>{
    let authorization = sessionStorage.getItem(token)
    let userInfo = sessionStorage.getItem(currentUser)
    if(authorization != null && userInfo != null){
        return ElMessage.warning('当前用户已登录,请勿重复登录')
    }
    router.push('/userLogin')
}
//退出登录
const userLogout = ()=>{
    ElMessageBox.confirm(
        '确定退出登录?',
        '警告提示',
        {
            confirmButtonText: '确定退出',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
        }
    ).then(() => {
        if(userInfo == null){
            return ElMessage.warning('登录信息为空,退出失败')
        }
        $http.get(`${gatewayPrefix}/${userMiddleContextPath}/userOperation/planetUserLogout?account=${userInfo.loginAccount}`).then((res)=>{
            if(res){
                ElMessage.success('退出成功')
                sessionStorage.clear()
                localStorage.clear()
                userInfo = null
                isLogin.value = true
                getAllFreeArtByPage()
                // router.push('/freePlanetIndex')
            }else{
                ElMessage.error(res.msg || '退出失败')
            }
        }).catch((err)=>{
            console.log('退出登录失败：',err);
            ElMessage.error('退出失败,请联系管理员')
        })
    }).catch(() => {
        ElMessage.info('取消操作')
    })
}
// 获取未登录时数据
const getAllFreeArtByPage = ()=>{
    $http.post(`${gatewayPrefix}/${userMiddleContextPath}/planetArticles/getLogoutArticleMainInfo`,leftArtDto).then(res=>{
        freeArtDataList.value = res
        if(freeArtDataList.value !== undefined && freeArtDataList.value.length > 0){
            currentArtId.value = freeArtDataList.value[0].articleId
            getArtDetailById()
            artDetailInfo.type=freeArtDataList.value[0].articleTypeName
            artDetailInfo.title=freeArtDataList.value[0].articleTitle
            getCommentList()
        }
    })
}
// 获取登录时数据
const getAllLoginArtByPage = ()=>{
    $http.post(`${gatewayPrefix}/${userMiddleContextPath}/planetArticles/getLoginArticleMainInfo`,leftArtDto).then(res=>{
        freeArtDataList.value = res
        if(freeArtDataList.value && freeArtDataList.value.length > 0){
            currentArtId.value = freeArtDataList.value[0].articleId
            getArtDetailById()
            artDetailInfo.type=freeArtDataList.value[0].articleTypeName
            artDetailInfo.title=freeArtDataList.value[0].articleTitle
            getCommentList()
            judgeCurrentArtIsCollect()
        }
    })
}
// 获取详情
const getArtDetailById = ()=>{
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/planetArticles/getArtDetailById?artId=${currentArtId.value}`).then(res=>{
        let detail=res
        artDetailInfo.articleContent=detail.articleContent
        artDetailInfo.articleId=detail.articleId
    })
    
}
// 点击展开详情按钮
const developArticleDetail = (val)=>{
    currentArtId.value=val.articleId
    currentArtUserId.value=val.userId
    artDetailInfo.type=val.articleTypeName
    artDetailInfo.title=val.articleTitle  
    getArtDetailById()
    getCommentList()      
    isDetail.value = !isDetail.value
    if(userInfo != null){
        judgeCurrentArtIsCollect()
    }   
    
}

const handleChange = (val) => {
    console.log(val)
}
// 左侧搜索
const leftSearchFnu = ()=>{
    getAllFreeArtByPage()
}
// 右侧搜索
const rightSearchFnu = ()=>{
    
}
// 子组件评论成功后的响应
const getCommentVal = (val)=>{
    if(val){
        getCommentList()
    }
}
// 获取评论
function getCommentList(){
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/planetArticles/getCommentList?artId=${currentArtId.value}`).then(res=>{
        commentList.value = res
    })
}
//刷新
const flushArtList = ()=>{
    if(userInfo == null){
        getAllFreeArtByPage()
    }else{
        getAllLoginArtByPage()
    }
    ElMessage.success('刷新成功')
}
//判断当前文章是否被当前用户收藏
const judgeCurrentArtIsCollect=()=>{
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/planetArticles/judgeCurrentArtIsCollect/${currentArtId.value}`).then(res=>{
        isCollect.value = res
    })
}
// 收藏
const collectArtFun=()=>{
    if(userInfo == null){
        return ElMessage.warning('用户未登录,请登录后操作!!!')
    }
    if(userInfo.userId == currentArtUserId.value){
        return ElMessage.warning('当前文章是您自己的文章,无须收藏!!!')
    }
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/planetArticles/collectArt/${currentArtId.value}`).then(res=>{
        if(res){
            judgeCurrentArtIsCollect()
            ElMessage.success('收藏成功')
        }else{
            ElMessage.error('收藏失败,请重试')
        }
    })
    
}
// 取消收藏
const cancelCollectArtFun = ()=>{
    ElMessageBox.confirm(
        '点击取消收藏,确认继续?',
        'Warning',
        {
            confirmButtonText: '确定取消',
            cancelButtonText: '不了,谢谢',
            type: 'warning',
        }
    ).then(() => {
        $http.get(`${gatewayPrefix}/${userMiddleContextPath}/planetArticles/cancelCollectArt/${currentArtId.value}`).then(res=>{
            if(res){
                judgeCurrentArtIsCollect()
                ElMessage.success('取消关注成功')
            }else{
                ElMessage.error('取消失败,请重试')
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: 'canceled',
        })
    })
    
}
// 获取角色信息
const getRolesByUserId = async ()=>{
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/planetMenus/getRolesByUserId/${userInfo.userId}`).then((result)=>{  
        if(result === undefined || result === null || result.length === 0){
            return ElMessage.error("获取当前用户角色错误,请联系管理员!!!")
        }     
        roleList.value = result        
    }) 
}
// 后台管理
const manageAdmin = async ()=>{
    if(userInfo === undefined || userInfo === null){
        return ElMessage.warning('用户登录信息为空,请先登录')
    }
    await getRolesByUserId()
    if(roleList.value.length === 1){
        sessionStorage.setItem("currentRole",roleList.value[0])
        router.push('/planetAdmin')
    }else{
        return ElMessage.warning('当前账户存在多个角色,请选择角色信息后再跳转后台')
    }
    
}
// 切换角色
const changeRole = ()=>{
    if(userInfo === undefined || userInfo === null){
        return ElMessage.warning('用户登录信息为空,请先登录')
    }
    getRolesByUserId()
    roleDialogVisible.value=true
}
// 确认角色
const confirmLogin = ()=>{
    if(selectRoleId.value === null || selectRoleId.value === undefined || selectRoleId.value === ''){
        return ElMessage.warning('请选择角色信息')
    }
    roleDialogVisible.value=false
    sessionStorage.setItem("currentRole",selectRoleId.value)
    ElMessage.warning("角色切换成功,请完善个人信息")           
    router.push('/planetAdmin')
}
// 联系客服
const contactConsumeService = ()=>{
    
}
</script>

<style src='../../assets/css/freePlanetIndex.css'></style>